package com.iotp.controller.admin.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iotp.controller.admin.base.BaseController;
import com.iotp.entity.base.DataMessage;
import com.iotp.entity.base.KKpager;
import com.iotp.entity.base.TreeData;
import com.iotp.entity.role.Role;
import com.iotp.entity.user.CommUser;
import com.iotp.entity.userRoleRef.UserRoleRef;
import com.iotp.service.role.RoleService;
import com.iotp.service.user.UserService;
import com.iotp.service.userRoleRef.UserRoleRefService;
import com.iotp.utils.common.DataUtil;
import com.iotp.utils.common.WyConstant;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


/**
 * 系统用户管理控制器
 * @author Assassin
 */
@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;// 系统用户业务接口
    @Autowired
    private RoleService roleService;// 系统角色业务接口
    @Autowired
    private UserRoleRefService userRoleRefService;// 用户-角色-关联业务接口

    /**
     * 进入系统用户列表页面
     * @return sys/user/list_user
     */
    @GetMapping("/list")
    public String gotoListPage() {
        return "admin/sys/user/list_user";
    }

    /**
     * 进入系统用户添加页面
     * @return sys/user/add_user
     */
    @GetMapping("/toAdd")
    public String gotoAddPage() {
        List<Role> roleList = this.roleService.queryList(null, null, getOrgType(), getOrgId(), null, 0,
                null, null, null, null, null);
        List<TreeData> treeDataList = new ArrayList<TreeData>();
        treeDataList.add(new TreeData("0", null, "用户角色[选择用户所属角色]", false, true));
        for (Role role : roleList) {
            treeDataList.add(new TreeData(role.getRoleId().toString(), "0", role.getRoleName() + "[" + (role.getRoleDesc() == null || "".equals(role.getRoleDesc().trim()) ? "—"  : role.getRoleDesc()) + "]", false, true));
        }
        request.setAttribute("treeData",JSONArray.toJSONString(treeDataList));
        return "admin/sys/user/add_user";
    }

    /**
     * 进入系统用户编辑页面
     * @param userId 用户Id
     * @return sys/user/edit_user
     */
    @GetMapping("/toEdit")
    public String gotoEditPage(@RequestParam(required = true, value = "userId") String userId) {
        // 后台数据验证
        if(!this.validateStringProperty(userId, 50, true)) {
            // TODO 错误页面
            return "redirect:/error";
        }
        CommUser editUser = this.userService.queryUserById(userId);
        if(editUser == null) {
            return "redirect:/error";
        }
        List<Role> roleList = this.roleService.queryList(null, null, getOrgType(), getOrgId(), null, 0,
                null, null, null, null, null);
        List<UserRoleRef> refList = this.userRoleRefService.queryList(editUser.getNewuserId());
        List<TreeData> treeDataList = new ArrayList<TreeData>();
        treeDataList.add(new TreeData("0", null, "用户角色[选择用户所属角色]", false, true));
        for (Role role : roleList) {
            boolean isChecked = false;
            for(UserRoleRef ref : refList) {
                if(role.getRoleId().longValue() == ref.getRoleId().longValue()) {
                    isChecked = true;
                    break;
                }
            }
            treeDataList.add(new TreeData(role.getRoleId().toString(), "0",
                    role.getRoleName() + "[" + (role.getRoleDesc() == null || "".equals(role.getRoleDesc().trim())
                            ? "—" : role.getRoleDesc()) + "]",
                    isChecked, true));
        }
        request.setAttribute("treeData",JSONArray.toJSONString(treeDataList));
        request.setAttribute("editUser", editUser);
        return "admin/sys/user/edit_user";
    }

    /**
     * 进入系统用户密码编辑页面
     * @param userId 用户Id
     * @return sys/user/edit_user
     */
    @GetMapping("/toEditPswd")
    public String gotoEditPswdPage(@RequestParam(required = true, value = "userId") String userId) {
        // 后台数据验证
        if(!this.validateStringProperty(userId, 50, true)) {
            // TODO 错误页面
            return "redirect:/error";
        }
        CommUser editUser = this.userService.queryUserById(userId);
        if(editUser == null) {
            return "redirect:/error";
        }
        request.setAttribute("editUser", editUser);
        return "admin/sys/user/edit_user_pswd";
    }

    /**
     * 进入修改密码页面
     * @return main/edit_pswd
     */
    @GetMapping("/toEditMySelfPswd")
    public String gotoEditMySelftPswdPage() throws Exception {
        return "admin/sys/user/edit_myself_pswd";
    }

    /**
     * 进入编辑个人信息页面
     * @return main/edit_myself
     */
    @GetMapping("/toEditMySelf")
    public String gotoEditMySelfPaeg() throws Exception {
        CommUser editUser = this.userService.queryUserById(getOldUserId());
        request.setAttribute("editUser", editUser);
        return "admin/sys/user/edit_myself";
    }

    /**
     * 加载系统用户表格数据
     * @param pageNo 当前页码
     * @param pageSize 每页记录数
     * @param account 账号
     * @param nickName 昵称
     * @param realName 真实姓名
     * @param email 电子邮箱
     * @param userStatus 用户状态
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/dataTable")
    public DataMessage selectTreeTable(
            @RequestParam(required = false, value = "pageNo") Integer pageNo,
            @RequestParam(required = false, value = "pageSize") Integer pageSize,
            @RequestParam(required = false, value = "account") String account,
            @RequestParam(required = false, value = "nickName") String nickName,
            @RequestParam(required = false, value = "realName") String realName,
            @RequestParam(required = false, value = "email") String email,
            @RequestParam(required = false, value = "userStatus") Integer userStatus
    ) {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        PageHelper.startPage(getPageNo(pageNo), getPageSize(pageSize));
//        PageHelper.orderBy("user_code");
        CommUser query = new CommUser();
        query.setAvailable(userStatus);
        query.setUserNameCn(realName);
        query.setEmail(email);
        query.setItCode(account);
        List<CommUser> userList = this.userService.queryByConditiono(query);
//        List<CommUser> userList = this.userService.queryList(null, null, getOrgType(), userStatus, 0, null, nickName, realName, null,
//                email, null, account, null, null, null, null, null, null);
        PageInfo<CommUser> pageInfo = new PageInfo<CommUser>(userList);
        dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
        dm.setData(userList);
        KKpager pager = new KKpager(getPageNo(pageNo), pageInfo.getPages() , pageInfo.getTotal());
        dm.setMessage(JSONObject.toJSON(pager).toString());
        return dm;
    }

    /**
     * 验证用户原始密码是否正确
     * @param oldPassword 原始密码
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/validateOldPswd")
    public DataMessage validateOldPswd(
            @RequestParam(required = true, value = "oldPassword") String oldPassword) throws ParseException {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(oldPassword, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("原始密码参数错误");
        } else {
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            CommUser user = this.userService.queryByUserIdAndPswd(getOldUserId(), oldPassword);
            if(user == null) {
                dm.setData("0");
            } else {
                dm.setData("1");
            }
        }
        return dm;
    }

    /**
     * 验证用户是否存在
     * @param userId 用户Id
     * @param account 用户账号
     * @param email 电子邮箱
     * @param -validateType[account | email]
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/validateIsUserExist")
    public DataMessage validateIsUserExist(
            @RequestParam(required = false, value = "userId") String userId,
            @RequestParam(required = false, value = "account") String account,
            @RequestParam(required = false, value = "email") String email,
            @RequestParam(required = true, value = "validateType") String validateType) throws ParseException {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(validateType, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("验证类型参数错误");
        } else if(!this.validateStringProperty(userId, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户标识参数错误");
        } else if(!this.validateStringProperty(account, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户账号参数错误");
        } else if(!this.validateStringProperty(email, 255, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("电子邮箱参数错误");
        } else {
//            Long uid = null;
//            if(userId != null && !"".equals(userId.trim())) {
//                uid = Long.parseLong(userId);
//            }
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            List<CommUser> userList = this.userService.queryIsUserExist(userId, account, email);
            if(userList == null || userList.size() == 0) {
                dm.setData("0");
            } else {
                dm.setData("1");
            }
        }
        return dm;
    }

    /**
     * 添加系统用户
     * @return DataMessage
     * @throws ParseException
     */
    @ResponseBody
    @PostMapping("/add")
    public DataMessage add(
            @RequestParam(required = false, value = "realName") String realName,
            @RequestParam(required = false, value = "userSex") String userSex,
            @RequestParam(required = false, value = "telphone") String telphone,
            @RequestParam(required = false, value = "email") String email,
            @RequestParam(required = false, value = "userDesc") String userDesc,
            @RequestParam(required = true, value = "account") String account,
            @RequestParam(required = false, value = "useDefaultPswd") String useDefaultPswd,
            @RequestParam(required = true, value = "roleIds") String roleIds,
            @RequestParam(required = false, value = "password") String password) throws ParseException {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(realName, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("真实姓名参数错误");
        } else if(!this.validateStringProperty(userSex, 1, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户性别参数错误");
        } else if(!this.validateStringProperty(telphone, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户手机参数错误");
        } else if(!this.validateStringProperty(email, 255, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("电子邮箱参数错误");
        } else if(!this.validateStringProperty(account, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("登录名参数错误");
        } else if(!this.validateStringProperty(useDefaultPswd, 1, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("默认密码参数错误");
        } else if(!this.validateStringProperty(password, 50, true) && (useDefaultPswd == null || "".equals(useDefaultPswd.trim()))) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("登录密码参数错误");
        } else if(!this.validateStringProperty(roleIds, 128, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户角色参数错误");
        } else {
            boolean isExist = false;
            List<CommUser> userList = this.userService.queryIsUserExist(null, account, null);
            if(userList != null && userList.size() > 0) {
                dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
                dm.setMessage("用户账号已经存在");
                isExist = true;
                return dm;
            }
            if(email != null && !"".equals(email)) {
                userList = this.userService.queryIsUserExist(null, null, email);
                if(userList != null && userList.size() > 0) {
                    dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
                    dm.setMessage("电子邮箱已经存在");
                    isExist = true;
                    return dm;
                }
            }
            if(!isExist) {
                Integer sex = null;
                if(userSex != null && !"".equals(userSex.trim())) {
                    sex = Integer.parseInt(userSex);
                }
//                Long userBirthday = null;
//                if(birthday != null && !"".equals(birthday.trim())) {
//                    userBirthday = new SimpleDateFormat("yyyy-MM-dd").parse(birthday).getTime();
//                }
                String userId = DataUtil.getUUID(1);
                CommUser add = new CommUser();
                add.setUserId(userId);
                add.setUserNameCn(realName);
                add.setSex(sex);
                add.setMobile(telphone);
                add.setNotes(userDesc);
                add.setItCode(account);
                add.setUserPassword((password == null || "".equals(password.trim()) ? DataUtil.generateMD5("123456".getBytes()): DataUtil.generateMD5(password.getBytes())));
                add.setRoleIds(roleIds);
                add.setOrgId(getOrgId());
                this.userService.add(add);
//                Long userId = this.userService.add(getOrgId(), getOrgCode(), getOrgType(), nickName, realName, sex, userBirthday, null, email, userDesc, account,null, password, roleIds);
                dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
                dm.setData(userId);
                dm.setMessage("用户添加成功");
            }
        }
        return dm;
    }

    /**
     * 编辑系统用户
     * @param userId 用户Id
     * @param realName 真实姓名
     * @param userSex 用户性别
     * @param email 电子邮箱
     * @param userDesc 用户说明
     * @param roleIds 角色Ids
     * @return DataMessage
     * @throws ParseException
     */
    @ResponseBody
    @PostMapping("/edit")
    public DataMessage edit(
            @RequestParam(required = true, value = "userId") String userId,
            @RequestParam(required = false, value = "realName") String realName,
            @RequestParam(required = false, value = "userSex") String userSex,
            @RequestParam(required = false, value = "telphone") String telphone,
            @RequestParam(required = false, value = "email") String email,
            @RequestParam(required = false, value = "userDesc") String userDesc,
            @RequestParam(required = true, value = "roleIds") String roleIds) throws ParseException {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userId, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Id参数错误");
        } else if(!this.validateStringProperty(realName, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("真实姓名参数错误");
        } else if(!this.validateStringProperty(userSex, 1, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户性别参数错误");
        } else if(!this.validateStringProperty(telphone, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户电话参数错误");
        } else if(!this.validateStringProperty(email, 255, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("电子邮箱参数错误");
        } else if(!this.validateStringProperty(roleIds, 128, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户角色参数错误");
        } else {
            boolean isExist = false;
            if(email != null && !"".equals(email)) {
                List<CommUser> userList = this.userService.queryIsUserExist(userId, null, email);
                if(userList != null && userList.size() > 0) {
                    dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
                    dm.setMessage("电子邮箱已经存在");
                    isExist = true;
                }
            }
            if(!isExist) {
                Integer sex = null;
                if(userSex != null && !"".equals(userSex.trim())) {
                    sex = Integer.parseInt(userSex);
                }
//                Long userBirthday = null;
//                if(birthday != null && !"".equals(birthday.trim())) {
//                    userBirthday = new SimpleDateFormat("yyyy-MM-dd").parse(birthday).getTime();
//                }
                CommUser edit = new CommUser();
                edit.setUserId(userId);
                edit.setOrgId(getOrgId());
                edit.setUserNameCn(realName);
                edit.setSex(sex);
                edit.setEmail(email);
                edit.setNotes(userDesc);
                edit.setRoleIds(roleIds);
                this.userService.edit(edit);
//                this.userService.edit(Long.parseLong(userId), getOrgId(), null, null, null, nickName, realName, sex, userBirthday, null, email, userDesc, roleIds);
                dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
                dm.setMessage("用户编辑成功");
            }
        }
        return dm;
    }

    /**
     * 编辑系统用户
     * @param realName 真实姓名
     * @param userSex 用户性别
     * @param email 电子邮箱
     * @param userDesc 用户说明
     * @return DataMessage
     * @throws ParseException
     */
    @ResponseBody
    @PostMapping("/editMySelf")
    public DataMessage editMySelf(
            @RequestParam(required = false, value = "realName") String realName,
            @RequestParam(required = false, value = "userSex") String userSex,
            @RequestParam(required = false, value = "telphone") String telphone,
            @RequestParam(required = false, value = "email") String email,
            @RequestParam(required = false, value = "userDesc") String userDesc) throws ParseException {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(realName, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("真实姓名参数错误");
        } else if(!this.validateStringProperty(userSex, 1, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户性别参数错误");
        } else if(!this.validateStringProperty(telphone, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户电话参数错误");
        } else if(!this.validateStringProperty(email, 255, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("电子邮箱参数错误");
        } else {
            Integer sex = null;
            if(userSex != null && !"".equals(userSex.trim())) {
                sex = Integer.parseInt(userSex);
            }
//            Long userBirthday = null;
//            if(birthday != null && !"".equals(birthday.trim())) {
//                userBirthday = new SimpleDateFormat("yyyy-MM-dd").parse(birthday).getTime();
//            }
            CommUser edit = new CommUser();
            edit.setUserId(getOldUserId());
            edit.setUserNameCn(realName);
            edit.setSex(sex);
            edit.setEmail(email);
            edit.setNotes(userDesc);
            this.userService.editMySelf(edit);
//            this.userService.editMySelf(getUserId(), nickName, realName, sex, userBirthday, null, email, userDesc);
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("个人信息编辑成功");
        }
        return dm;
    }

    /**
     * 编辑系统用户密码
     * @param userId 用户Id
     * @param password 登录密码
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/editPswd")
    public DataMessage editPswd(
            @RequestParam(required = true, value = "userId") String userId,
            @RequestParam(required = true, value = "password") String password) throws ParseException {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userId, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Id参数错误");
        } else if(!this.validateStringProperty(password, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("登录密码参数错误");
        } else {
            this.userService.editPswd(userId, password);
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户密码编辑成功");
        }
        return dm;
    }

    /**
     * 编辑个人密码
     * @param oldPassword 原始密码
     * @param password 新的密码
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/editMySelfPswd")
    public DataMessage editMySelfPswd(
            @RequestParam(required = true, value = "oldPassword") String oldPassword,
            @RequestParam(required = true, value = "password") String password) throws ParseException {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(oldPassword, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("原始密码参数错误");
        } else if(!this.validateStringProperty(password, 50, false)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("新的密码参数错误");
        } else {
            CommUser user = this.userService.queryByUserIdAndPswd(getOldUserId(), oldPassword);
            if(user == null) {
                dm.setResult(WyConstant.RESULT_CODE_DATA_ERROR);
                dm.setMessage("原始密码参数错误");
            } else {
                this.userService.editPswd(getOldUserId(), password);
                dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
                dm.setMessage("密码修改成功");
            }
        }
        return dm;
    }

    /**
     * 启用系统用户
     * @param userId 用户Id
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/enable")
    public DataMessage enable(@RequestParam(required = true, value = "userId") String userId) {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userId, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Id参数错误");
        } else {
            this.userService.editUserStatus(userId, 1);
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户启用成功");
        }
        return dm;
    }

    /**
     * 批量启用系统用户
     * @param userIds 用户Ids
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/batchEnable")
    public DataMessage enableBatch(@RequestParam(required = true, value = "userIds") String userIds) {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userIds, 128, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Ids参数错误");
        } else {
            String[] userIdsArr = userIds.split(",");
            for(String userId : userIdsArr) {
                this.userService.editUserStatus(userId, 1);
            }
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户启用成功");
        }
        return dm;
    }

    /**
     * 禁用系统用户
     * @param userId 用户Id
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/disable")
    public DataMessage disable(@RequestParam(required = true, value = "userId") String userId) {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userId, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Id参数错误");
        } else {
            this.userService.editUserStatus(userId, 0);
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户禁用成功");
        }
        return dm;
    }

    /**
     * 批量禁用系统用户
     * @param userIds 用户Ids
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/batchDisable")
    public DataMessage disableBatch(@RequestParam(required = true, value = "userIds") String userIds) {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userIds, 128, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Ids参数错误");
        } else {
            String[] userIdsArr = userIds.split(",");
            for(String userId : userIdsArr) {
                this.userService.editUserStatus(userId, 0);
            }
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户禁用成功");
        }
        return dm;
    }

    /**
     * 删除系统用户
     * @param userId 用户Id
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/delete")
    public DataMessage delete(@RequestParam(required = true, value = "userId") String userId) {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userId, 50, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Id参数错误");
        } else {
            this.userService.editIsDel(userId, 1);
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户删除成功");
        }
        return dm;
    }

    /**
     * 批量删除系统用户
     * @param userIds 用户Ids
     * @return DataMessage
     */
    @ResponseBody
    @PostMapping("/batchDelete")
    public DataMessage deleteBatch(@RequestParam(required = true, value = "userIds") String userIds) {
        // 返回数据消息实体
        DataMessage dm = new DataMessage();
        // 后台数据验证
        if(!this.validateStringProperty(userIds, 128, true)) {
            dm.setResult(WyConstant.RESULT_CODE_PARAMETER_ERROR);
            dm.setMessage("用户Ids参数错误");
        } else {
            String[] userIdsArr = userIds.split(",");
            for(String userId : userIdsArr) {
                this.userService.editIsDel(userId, 1);
            }
            dm.setResult(WyConstant.RESULT_CODE_SUCCESS);
            dm.setMessage("用户删除成功");
        }
        return dm;
    }

    /**
     * 导出数据到Excel
     * @param account 账号
     * @param nickName 昵称
     * @param realName 真实姓名
     * @param email 电子邮箱
     * @param userStatus 用户状态
     * @return Excel File
     * @throws Exception
     */
    @PostMapping("/export")
    public ModelAndView exportExcel(
            @RequestParam(required = false, value = "account") String account,
            @RequestParam(required = false, value = "nickName") String nickName,
            @RequestParam(required = false, value = "realName") String realName,
            @RequestParam(required = false, value = "email") String email,
            @RequestParam(required = false, value = "userStatus") Integer userStatus
    ) throws Exception {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("系统用户信息");
        // 手动设置列宽。第一个参数表示要为第几列设；，第二个参数表示列的宽度，n为列高的像素数。
        sheet.setColumnWidth((short) 0, (short) (15.7 * 150));
        sheet.setColumnWidth((short) 1, (short) (25.7 * 150));
        sheet.setColumnWidth((short) 2, (short) (35.7 * 150));
        sheet.setColumnWidth((short) 3, (short) (35.7 * 150));
        sheet.setColumnWidth((short) 4, (short) (35.7 * 150));
        sheet.setColumnWidth((short) 5, (short) (35.7 * 150));
        sheet.setColumnWidth((short) 6, (short) (35.7 * 150));
        sheet.setColumnWidth((short) 7, (short) (35.7 * 150));
        sheet.setColumnWidth((short) 8, (short) (35.7 * 150));
        // 创建第一行
        Row row = sheet.createRow((short) 0);
        // 创建两种单元格格式
        CellStyle cs = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();

        // 创建两种字体
        Font f = wb.createFont();
        Font f2 = wb.createFont();

        // 创建第一种字体样式
        f.setFontHeightInPoints((short) 12);
        f.setColor(IndexedColors.BLACK.getIndex());
        f.setBoldweight(Font.BOLDWEIGHT_BOLD);
        // 创建第二种字体样式
        f2.setFontHeightInPoints((short) 11);
        f2.setColor(IndexedColors.BLACK.getIndex());
        f2.setBoldweight(Font.BOLDWEIGHT_NORMAL);

        // 设置第一种单元格的样式
        cs.setFont(f);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        // 设置第二种单元格的样式
        cs2.setFont(f2);
        cs2.setBorderLeft(CellStyle.BORDER_THIN);
        cs2.setBorderRight(CellStyle.BORDER_THIN);
        cs2.setBorderTop(CellStyle.BORDER_THIN);
        cs2.setBorderBottom(CellStyle.BORDER_THIN);
        cs2.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        // 创建列（每行里的单元格）
        Cell cell = row.createCell(0);
        cell.setCellValue("序号");
        cell.setCellStyle(cs);

        cell = row.createCell(1);
        cell.setCellValue("用户编码");
        cell.setCellStyle(cs);

        cell = row.createCell(2);
        cell.setCellValue("用户账号");
        cell.setCellStyle(cs);

        cell = row.createCell(3);
        cell.setCellValue("用户姓名");
        cell.setCellStyle(cs);

        cell = row.createCell(4);
        cell.setCellValue("用户性别");
        cell.setCellStyle(cs);

        cell = row.createCell(5);
        cell.setCellValue("用户生日");
        cell.setCellStyle(cs);

        cell = row.createCell(6);
        cell.setCellValue("用户昵称");
        cell.setCellStyle(cs);

        cell = row.createCell(7);
        cell.setCellValue("电子邮箱");
        cell.setCellStyle(cs);

        cell = row.createCell(8);
        cell.setCellValue("用户说明");
        cell.setCellStyle(cs);

        cell = row.createCell(9);
        cell.setCellValue("用户状态");
        cell.setCellStyle(cs);

        PageHelper.orderBy("create_time DESC");
        CommUser query = new CommUser();
        query.setAvailable(userStatus);
        query.setUserNameCn(realName);
        query.setEmail(email);
        query.setItCode(account);
        List<CommUser> userList = this.userService.queryByConditiono(query);
//        List<CommUser> userList = this.userService.queryList(null, null, getOrgType(), userStatus, 0, null, nickName, realName, null,
//                email, null, account, null, null, null, null, null, null);
        for(int i = 0; i < userList.size(); i++) {
            CommUser user = userList.get(i);
            row = sheet.createRow(i + 1);
            cell = row.createCell(0);
            cell.setCellValue(i + 1);
            cell.setCellStyle(cs2);

            cell = row.createCell(1);
//            cell.setCellValue(user.getUserCode());
            cell.setCellStyle(cs2);

            cell = row.createCell(2);
            cell.setCellValue(user.getItCode());
            cell.setCellStyle(cs2);

            cell = row.createCell(3);
            cell.setCellValue((user.getUserNameCn() == null || "".equals(user.getUserNameCn().trim())) ? "—" : user.getUserNameCn());
            cell.setCellStyle(cs2);

            cell = row.createCell(4);
            cell.setCellValue((user.getSex().intValue() == 1) ? "男" : "女");
            cell.setCellStyle(cs2);

//            cell = row.createCell(5);
//            cell.setCellValue((user.getBirthday() == null) ? "—" : DataUtil.long2date(user.getBirthday(), "yyyy-MM-dd"));
//            cell.setCellStyle(cs2);

//            cell = row.createCell(6);
//            cell.setCellValue((user.getNickName() == null || "".equals(user.getNickName().trim())) ? "—" : user.getNickName());
//            cell.setCellStyle(cs2);

            cell = row.createCell(7);
            cell.setCellValue((user.getEmail() == null || "".equals(user.getEmail().trim())) ? "—" : user.getEmail());
            cell.setCellStyle(cs2);

//            cell = row.createCell(8);
//            cell.setCellValue((user.getUserDesc() == null || "".equals(user.getUserDesc().trim())) ? "—" : user.getUserDesc());
//            cell.setCellStyle(cs2);

//            cell = row.createCell(9);
//            if(user.getUserStatus().intValue() == 1) {
//                cell.setCellValue("已启用");
//            } else {
//                cell.setCellValue("已禁用");
//            }
            cell.setCellStyle(cs2);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            wb.write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("系统用户信息" + ".xls").getBytes(), "ISO-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        return null;
    }

}